<template>
  <div class="register-page">
    <div class="register-container">
      <div class="register-header">
        <h2>AI Cloud</h2>
        <p class="subtitle">创建新账号</p>
      </div>
      <el-form :model="registerForm" :rules="rules" ref="registerFormRef" class="register-form">
        <el-form-item prop="username">
          <el-input 
            v-model="registerForm.username" 
            placeholder="用户名" 
            prefix-icon="el-icon-user"
            size="large"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input 
            v-model="registerForm.password" 
            type="password" 
            placeholder="密码" 
            prefix-icon="el-icon-lock"
            size="large"
          ></el-input>
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input 
            v-model="confirmPassword" 
            type="password" 
            placeholder="确认密码" 
            prefix-icon="el-icon-lock"
            size="large"
          ></el-input>
        </el-form-item>
        <el-form-item prop="phone">
          <el-input 
            v-model="registerForm.phone" 
            placeholder="手机号（选填）" 
            prefix-icon="el-icon-phone"
            size="large"
          ></el-input>
        </el-form-item>
        <el-form-item prop="captcha">
          <div class="captcha-row">
            <el-input 
              v-model="registerForm.captcha" 
              placeholder="验证码" 
              class="captcha-input"
              size="large"
            ></el-input>
            <img 
              :src="captchaUrl" 
              @click="refreshCaptcha" 
              class="captcha-image" 
              alt="验证码" 
              title="点击刷新验证码" 
            />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleRegister" 
            :loading="loading" 
            class="register-button"
            size="large"
          >注册</el-button>
        </el-form-item>
        <div class="login-link">
          <router-link to="/login">已有账号？立即登录</router-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getCaptcha, register } from '../../services/auth';
import type { RegisterParams } from '../../services/auth';

const router = useRouter();
const registerFormRef = ref();
const captchaUrl = ref('');
const loading = ref(false);
const confirmPassword = ref('');

const registerForm = reactive<RegisterParams>({
  username: '',
  password: '',
  captcha: '',
  phone: ''
});

const validatePass = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'));
  } else {
    if (confirmPassword.value !== '') {
      registerFormRef.value?.validateField('confirmPassword');
    }
    callback();
  }
};

const validatePass2 = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致!'));
  } else {
    callback();
  }
};

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, validator: validatePass, trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePass2, trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
};

const refreshCaptcha = async () => {
  try {
    const res = await getCaptcha();
    captchaUrl.value = res.data + '?t=' + new Date().getTime();
  } catch (error) {
    ElMessage.error('获取验证码失败');
  }
};

const handleRegister = async () => {
  if (!registerFormRef.value) return;
  
  await registerFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      try {
        const res = await register(registerForm);
        ElMessage.success('注册成功，请登录');
        router.push('/login');
      } catch (error: any) {
        ElMessage.error(error.message || '注册失败');
        refreshCaptcha();
      } finally {
        loading.value = false;
      }
    }
  });
};

onMounted(() => {
  refreshCaptcha();
});
</script>

<style scoped>
.register-page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.register-container {
  width: 100%;
  max-width: 450px;
  padding: 40px;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  background-color: #fff;
  transition: all 0.3s ease;
}

.register-header {
  text-align: center;
  margin-bottom: 40px;
}

h2 {
  margin: 0;
  color: #409eff;
  font-size: 32px;
  font-weight: 600;
}

.subtitle {
  margin-top: 8px;
  color: #909399;
  font-size: 16px;
}

.register-form {
  margin-top: 20px;
}

.captcha-row {
  display: flex;
  align-items: center;
  gap: 12px;
}

.captcha-input {
  flex: 1;
}

.captcha-image {
  cursor: pointer;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  padding: 2px;
  width: 120px;
  height: 44px;
  transition: all 0.3s;
}

.captcha-image:hover {
  border-color: #409eff;
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.2);
}

.register-button {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 500;
  margin-top: 10px;
  border-radius: 6px;
}

.login-link {
  text-align: center;
  margin-top: 24px;
}

.login-link a {
  color: #409eff;
  text-decoration: none;
  font-size: 14px;
  transition: all 0.3s;
}

.login-link a:hover {
  color: #66b1ff;
  text-decoration: underline;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .register-page {
    padding: 15px;
    background: #fff;
  }
  
  .register-container {
    max-width: 100%;
    padding: 20px;
    box-shadow: none;
  }
  
  h2 {
    font-size: 28px;
  }
}
</style> 